package com.king.base.algor.table.sequence;

import java.lang.reflect.Array;

/**
 * 描述:顺序表的插入删除
 * <p>
 * 假定长度为n的顺序表占据数组a[m]的前n个单元a[0]~a[n-1](n<=m)
 *
 * @author : sujinchen
 * @date : 2021/10/26
 */
public class InsertOrDele {

    private int m = 20;

    private int maxN = m - 1;

    private int curN = 0;

    private int a[] = new int[m];


    /**
     * >>无条件插入
     * 表尾插入最为方便
     *
     * @param point
     */
    public int insert(int point) {
        if (!verifyIndex()) {
            return 0;
        }
        a[curN] = point;
        curN++;
        return 1;
    }

    /**
     * >>指定位置插入
     * 从第index个元素开始右移
     *
     * @param point
     * @param index
     */
    public int insert(int point, int index) {
        if (!verifyIndex()) {
            return 0;
        }
        for (int i = curN; i > index; i--) {
            a[i] = a[i - 1];
        }
        a[index] = point;
        curN++;
        return 1;
    }


    /**
     * >>按指定条件插入
     * 在有序表中插入，边找边插
     * @param point
     * @return
     */
    public int insertBySequence(int point) {
        if (!verifyIndex()) {
            return 0;
        }
        int i;
        for (i = curN; point < a[i] && i > 0; i--) {
            a[i] = a[i - 1];
        }
        a[i] = point;
        curN++;
        return 1;
    }


    /**
     * 验证下标是否越界
     *
     * @return
     */
    private boolean verifyIndex() {
        return curN <= maxN;
    }


    /**
     * >>删除非指定结点
     * 删除表尾
     *
     * @return
     */
    public int del() {
        a[curN - 1] = 0;
        return 0;
    }

    /**
     * >>删除指定结点值
     *
     * @param point
     * @return
     */
    public int delByPoint(int point) {
        int index = 0;
        for (int i = 0; i < curN; i++) {
            if (point == a[i]) {
                index = i;
                break;
            }
        }
        if (index == 0 && index < curN) {
            return 0;
        }
        for (int i = index; i < curN; i++) {
            a[i] = a[i + 1];
        }
        return 1;
    }


    /**
     * >>删除指定位置的结点
     *
     * @param index
     * @return
     */
    public int delByIndex(int index) {
        if (index == 0 && index < curN) {
            return 0;
        }
        for (int i = index; i < curN; i++) {
            a[i] = a[i + 1];
        }
        return 1;
    }


    public void showData() {
        System.out.print("[ ");
        for (int i : a) {
            System.out.print(i+" ");
        }
        System.out.println("]");
    }

    public static void main(String[] args) {
        InsertOrDele insertOrDele = new InsertOrDele();
        insertOrDele.insert(1);
        insertOrDele.showData();
        insertOrDele.insert(2, 1);
        insertOrDele.showData();
        insertOrDele.insert(3, 2);
        insertOrDele.showData();
        insertOrDele.delByPoint(0);
        insertOrDele.showData();
        insertOrDele.delByIndex(4);
        insertOrDele.showData();
    }
}
